import { getUserInfo } from "@/utils/auth";

// 是否正在刷新token
let isRefreshing = false;
let requests: any = [];
let nowStart = new Date().getTime();
let times = 0;
console.log(isRefreshing, requests, nowStart, "刷新token");

export const refreshToken = (fn) => {
  if (!isRefreshing) {
    isRefreshing = true;
    return getUserInfo(true).then(() => {
      let nowEnd = new Date().getTime();
      times ++;
      if (nowEnd - nowStart > 3000 && times > 3) {
        nowStart = new Date().getTime();
        times = 0;
        requests = [];
        return
      }
      fn && fn();
      requests.forEach(fnItem => fnItem());
      requests = [];
    }).catch(err => {
      console.log("refreshToken is error:", err);
    }).finally(() => {
      isRefreshing = false;
    })
  } else {
    return new Promise((resolve) => {
      requests.push(() => {
        resolve(fn && fn());
      })
    })
  }
}